package com.lzx.reggie.common

import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.RestController
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import java.sql.SQLIntegrityConstraintViolationException

@ControllerAdvice(annotations = [RestController::class, Controller::class])
@ResponseBody
class GlobalExceptionHandler {
    companion object {
        private val log = LoggerFactory.getLogger(GlobalExceptionHandler::class.java)
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException::class)
    fun exceptionHandler(ex: SQLIntegrityConstraintViolationException): R<Any> {

        log.error(ex.message)

        if (ex.message!!.contains("Duplicate entry")) {
            val split = ex.message!!.split(" ")
            val msg = split[2] + "已存在"
            return R.error(msg)
        }
        return R.error("未知错误")
    }

    @ExceptionHandler(CustomException::class)
    fun exceptionHandler(ex: CustomException): R<Any> {

        log.error(ex.message)

        return R.error(ex.message)
    }
}